﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

namespace DoubanFM.Core
{
    /// <summary>
    /// 计划将其修改为多线程下载一首音乐的
    /// </summary>
    class Downloader
    {
        private static string path = Path.Combine(Environment.CurrentDirectory, "download");

        public static void Download(string url, string fileName)
        {
            new WebClient().DownloadFile(url, fileName + ".mp3");
        }

        internal static void Download(Song[] ls)
        {
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            if (!Directory.Exists(Path.Combine(path , "like"))) Directory.CreateDirectory(Path.Combine(path + "like"));

            foreach (Song s in ls)
            {
                string fileName = string.Empty;

                if (s.Like)
                    fileName = Path.Combine(path, "like\\" + s.Title + " - " + s.Artist + ".mp3");
                else
                    fileName = Path.Combine(path, s.Title + " - " + s.Artist + ".mp3");

                if (!File.Exists(fileName))
                {
                    try
                    {
                        new WebClient().DownloadFile(s.FileUrl, fileName);
                        Debug.WriteLine(s.Title + " - " + s.Artist + " 下载完成.");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                        try
                        {
                            File.Delete(fileName);
                        }
                        catch (Exception es)
                        {
                            Debug.WriteLine(es.Message);
                        }
                    }

                }
                if (IsFileInUse(fileName)) return;
                //加入音乐信息
                MediaTags tag = new MediaTags(fileName);
                tag.Author = s.Artist;
                tag.Title = s.Title;
                tag.AlbumTitle = s.Album;
                try
                {
                    tag.Commit(fileName);
                }
                catch (Exception)
                {
                }

            }
        }
        /// <summary>
        /// 检查文件是否被占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns>true表示正在使用,false没有使用</returns>
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                inUse = false;
            }
            catch { }
            finally
            {
                if (fs != null) fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }

        /// <summary>
        /// 检查音乐文件是否存在
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        internal static bool FileExists(Song s)
        {
            string fileName = string.Empty;

            if (s.Like)
                fileName = path + "like\\" + s.Title + " - " + s.Artist + ".mp3";
            else
                fileName = path + s.Title + " - " + s.Artist + ".mp3";

            if (!File.Exists(path + s.Title + " - " + s.Artist + ".mp3"))
                return true;

            return false;
        }

        /// <summary>
        /// 检查一下本地文件,如果文件存在就把Song的URL修改为本地的文件路径
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        internal static Song ChangeUrl(Song s)
        {
            string fileName = string.Empty;

            if (s.Like)
                fileName = path + "like\\" + s.Title + " - " + s.Artist + ".mp3";
            else
                fileName = path + s.Title + " - " + s.Artist + ".mp3";

            if (File.Exists(fileName))
                s.FileUrl = fileName;

            return s;
        }

        /// <summary>
        /// 替换网络URL为本地的,
        /// 顺便下载本地没有的音乐文件
        /// </summary>
        /// <param name="ls"></param>
        /// <returns></returns>
        internal static PlayList Replace(PlayList ls)
        {
            Song[] pl = new Song[ls.Count];
            ls.CopyTo(pl);
            //启用线程下载
            ThreadPool.QueueUserWorkItem(new WaitCallback(dowanloads =>
            {
                Download(pl);
            }));


            for (int i = 0; i < ls.Count; i++)
                ls[i] = ChangeUrl(ls[i]);

            return ls;
        }

    }
}
